package panels;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Stack;

import model.App;

public class CanvasLinePanel extends SPanel {
	private static final long serialVersionUID = -2063688345417664908L;
	private int width;
	private int height;
	private int point = 20;
	private double max = -1;
	private Stack<Double> hei = new Stack<Double>();

	public CanvasLinePanel() {
		System.out.println("canvas--------------");
		int size = App.packetList.size();
		int conb = size / point; // 最多point个点
		double tmp = 0;
		conb = conb < 1 ? 1 : conb;
		for (int i = 0; i < size; i++) {
			tmp += App.packetList.get(i).len / 1024.0;
			if ((i + 1) % conb == 0) {
				hei.push(tmp);
				System.out.println(hei.peek());
				tmp = 0;
				if (hei.peek() > max)
					max = hei.peek();
			}
		}
	}

	protected void paintComponent(Graphics g) {
		paintLines(g);
	}

	private void paintLines(Graphics g) {
		Graphics2D con = (Graphics2D) g;
		width = getWidth() - 1;
		height = getHeight() - 1;
		// 背景
		con.setColor(new Color(245, 245, 245));
		con.fillRect(0, 0, width, height);
		// 面积图
		int[] xs = new int[hei.size() + 2];
		int[] ys = new int[hei.size() + 2];
		int node_width = width / (hei.size() - 1);
		double max_hei = max * 1.2;
		xs[0] = width;
		ys[0] = height;
		xs[1] = 0;
		ys[1] = height;
		for (int i = 0; i < hei.size(); i++) {
			xs[i + 2] = i * node_width;
			ys[i + 2] = (int) ((max_hei - hei.get(i)) * height / max_hei);
		}
		xs[hei.size() + 1] = width;
		con.setColor(new Color(230, 240, 250));
		con.fillPolygon(xs, ys, hei.size() + 2);
		// 折线
		con.setColor(new Color(220, 220, 220));
		for (int i = 0; i < hei.size() - 1; i++) {
			con.drawLine(xs[i + 2], ys[i + 2], xs[i + 3], ys[i + 3]);
		}
		// 边框and参考线(5代表5条参考线)
		int lines_num = 5;
		con.setStroke(new BasicStroke(2));
		con.setFont(new Font(null, Font.PLAIN, 15));
		node_width = height / lines_num;
		max_hei = max_hei / lines_num;
		for (int i = 0; i < lines_num; i++) {
			con.setColor(new Color(220, 220, 220));
			con.drawLine(0, i * node_width, width, i * node_width);
			con.setColor(new Color(120, 120, 120));
			con.drawString(String.format("%.2f", max_hei * (lines_num - i)) + "KB", 10, i
					* node_width);
		}
		con.setColor(new Color(220, 220, 220));
		con.drawLine(0, 0, 0, height);
		con.drawLine(width, 0, width, height);
		con.drawLine(0, height, width, height);
	}
}
